package com.example.cloudzuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

@Component
@Slf4j
public class TestFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return -1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx =RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        if (request.getRequestURI().equals("?token")){
            byte[] encoded = null;
            try {
                //log.debug("用户认证登录");
                String authorization = ctx.getRequest().getHeader("Authorization");
                if (StringUtils.hasLength(authorization)) {
                    // log.debug("authorization");
                } else {
                    encoded = Base64.encode("browser:".getBytes("UTF-8"));
                    ctx.addZuulRequestHeader("Authorization", "Basic " + new String(encoded));
                }
            } catch (UnsupportedEncodingException e) {
                // log.error(e.getMessage());
            }
        } else {
            ctx.setSendZuulResponse(false); //不对其进行路由
            ctx.setResponseStatusCode(401);
            HttpServletResponse response = ctx.getResponse();
            response.setHeader("content-type", "text/html;charset=utf8");
            ctx.setResponseBody("网关认证失败，停止路由");
            ctx.set("code", 0);
        }
        return null;
    }
}
